#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 计算上一个周五的日期
问题: 你需要一个通用方法来计算一周中某一天上一次出现的日期，例如上一个周五的日期。
提示 : 
"""

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from dateutil.rrule import FR

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
            'Friday', 'Saturday', 'Sunday']


def recipe1():
    print(f"{datetime.today() = }")
    print(f"{get_previous_byday('Monday') = }")
    print(f"{get_previous_byday('Tuesday') = }")
    print(f"{get_previous_byday('Friday') = }")

    print(f"{get_previous_byday('Sunday', datetime(2012, 12, 21)) = }")


def recipe2():
    """执行大量的日期计算"""

    d = datetime.now()
    print(f"{d = }")
    # Next Friday
    print(f"{d + relativedelta(weekday=FR) = }")
    # Next Friday
    print(f"{d + relativedelta(weekday=FR(-1)) = }")

def get_previous_byday(dayname, start_date=None):
    if (start_date is None):
        start_date = datetime.today()
    day_num = start_date.weekday()
    day_num_target = weekdays.index(dayname)
    days_ago = (7 + day_num - day_num_target) % 7       # 模运算
    if days_ago == 0:
        days_ago = 7
    target_date = start_date - timedelta(days=days_ago)
    return target_date


def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()

if __name__ == '__main__':
    main()
